/*
 * Copyright (C) 2014 Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.bambole.util;

import com.googlecode.bambole.controller.util.JsfUtil;
import com.googlecode.bambole.controller.util.LocalizationUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Eduardo Pereira Montenegro <epereiramontenegro@gmail.com>
 */
public class SearchUtil {

    private static final SimpleDateFormat searchDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static String getTodayAsSearchParameter() {
        return "{d \'" + searchDateFormat.format(new Date()) + "\'}";
    }

    public static String getQueryClause(String fieldName, String userInput, char queryType, boolean queryAddAnd) {

        String queryClause = "*";

        SimpleDateFormat userInputDateFormat = new SimpleDateFormat(LocalizationUtil.getSearchDateFormatPattern(), JsfUtil.getLocale());

        if (isQueryClauseParamOk(fieldName, userInput, queryType)) {
            userInput = userInput.replace(" ", "");
            if (queryType == 'b') {
                switch (userInput) {
                    case "f":
                        queryClause = queryAddAnd ? " AND " : "";
                        queryClause = queryClause + fieldName + " = false";
                        break;
                    case "t":
                        queryClause = queryAddAnd ? " AND " : "";
                        queryClause = queryClause + fieldName + " = true";
                        break;
                    default:
                        queryClause = queryAddAnd ? " AND " : "";
                        queryClause = queryClause + "(" + fieldName + " = true OR " + fieldName + " = false)";
                }
            } else if (queryType != 'b' && !userInput.contains("...")) {
                String operand = userInput.startsWith(">") || userInput.startsWith("<") ? String.valueOf(userInput.charAt(0)) : "=";
                userInput = userInput.startsWith(">") || userInput.startsWith("<") ? userInput.substring(1) : userInput;
                if (queryType == 'n') {
                    try {
                        queryClause = queryAddAnd ? " AND " : "";
                        queryClause = queryClause + fieldName + " " + operand + " " + Integer.parseInt(userInput);
                    } catch (NumberFormatException e) {
                        Logger.getAnonymousLogger().log(Level.INFO, "Invalid number: {0}", e.getMessage());
                    }
                } else if (queryType == 'd') {
                    try {
                        userInputDateFormat.setLenient(false);
                        Date date = userInputDateFormat.parse(userInput);
                        queryClause = queryAddAnd ? " AND " : "";
                        queryClause = queryClause + fieldName + " " + operand + " {d \'" + searchDateFormat.format(date) + "\'}";
                    } catch (ParseException e) {
                        Logger.getAnonymousLogger().log(Level.INFO, "Invalid date: {0}", e.getMessage());
                    }
                }
            } else if (queryType != 'b' && userInput.contains("...")) {
                String[] params = userInput.split("\\...");
                String param1, param2;
                param1 = params[0];
                param2 = params[1];
                if (queryType == 'n') {
                    int p1 = Integer.parseInt(param1);
                    int p2 = Integer.parseInt(param2);
                    try {
                        if (p2 > p1) {
                            queryClause = queryAddAnd ? " AND " : "";
                            queryClause = queryClause + fieldName + " >= " + p1 + " AND " + fieldName + " <= " + p2;
                        }
                    } catch (NumberFormatException e) {
                        Logger.getAnonymousLogger().log(Level.INFO, "Invalid number: {0}", e.getMessage());
                    }
                } else if (queryType == 'd') {
                    try {
                        userInputDateFormat.setLenient(false);
                        Date date1 = userInputDateFormat.parse(param1);
                        Date date2 = userInputDateFormat.parse(param2);
                        if (date1.before(date2)) {
                            queryClause = queryAddAnd ? " AND " : "";
                            queryClause = queryClause + fieldName + " >= {d \'" + searchDateFormat.format(date1) + "\'} AND " + fieldName + " <= {d \'" + searchDateFormat.format(date2) + "\'}";
                        }
                    } catch (ParseException e) {
                        Logger.getAnonymousLogger().log(Level.INFO, "Invalid date: {0}", e.getMessage());
                    }
                }
            }
        }
        if (queryClause != null && !queryClause.isEmpty()) {
            return queryClause;
        } else {
            return null;
        }
    }

    private static boolean isQueryClauseParamOk(String fieldName, String userInput, char queryType) {

        boolean retVal = true;

        if (queryType != 'n' && queryType != 'd' && queryType != 'b') {
            retVal = false;
        } else if (fieldName == null || userInput == null) {
            retVal = false;
        } else if (fieldName.isEmpty() || userInput.isEmpty()) {
            retVal = false;
        } else if (fieldName.contains(" ")) {
            retVal = false;
        } else if (userInput.contains("...") && (userInput.contains("<") || userInput.contains(">"))) {
            retVal = false;
        } else if (userInput.contains("...") && (userInput.startsWith("...") || userInput.endsWith("..."))) {
            retVal = false;
        } else if ((userInput.contains("<") && !userInput.startsWith("<")) || (userInput.contains(">") && !userInput.startsWith(">"))) {
            retVal = false;
        }

        return retVal;
    }
}
